package io.wdb.modules.activity.wxapp.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.wdb.common.utils.UUIDGenerator;


import io.wdb.modules.activity.wxapp.dao.HdCardInitiatorDao;
import io.wdb.modules.activity.wxapp.dao.HdConfigDao;
import io.wdb.modules.activity.wxapp.entity.HdCardInitiatorEntity;
import io.wdb.modules.activity.wxapp.service.HdCardInitiatorService;



@Service("hdCardInitiatorService")
public class HdCardInitiatorServiceImpl implements HdCardInitiatorService {
	@Autowired
	private HdCardInitiatorDao hdCardInitiatorDao;
	
	@Autowired
	private HdConfigDao hdConfigDao;
	
	@Override
	public HdCardInitiatorEntity queryObject(String id){
		return hdCardInitiatorDao.queryObject(id);
	}
	
	@Override
	public List<HdCardInitiatorEntity> queryList(Map<String, Object> map){
		return hdCardInitiatorDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return hdCardInitiatorDao.queryTotal(map);
	}
	
	@Override
	public HdCardInitiatorEntity save(HdCardInitiatorEntity hdCardInitiator){
		Map<String, Object> map = new HashMap<>();
		map.put("userId", hdCardInitiator.getUserId());
		map.put("activityId", hdCardInitiator.getActivityId());
		List<HdCardInitiatorEntity> entities = hdCardInitiatorDao.queryList(map);
		
		if (entities != null && entities.size() >= Integer.valueOf(hdConfigDao.queryObject("cardActivityTimes").getHdValue())) {
			hdCardInitiator.setId(entities.get(0).getId());
			return hdCardInitiator;
		}
		
		map.put("account", 0);//查询未到账数据
		entities = hdCardInitiatorDao.queryList(map);
		//TODO 获取这次活动可以参与几次，如果超过次数，就不再新增
		if(entities != null && entities.size() > 0) {
			hdCardInitiator.setId(entities.get(0).getId());
//			hdCardInitiatorDao.update(hdCardInitiator);
		}else {
			hdCardInitiator.setId(UUIDGenerator.getUUID());
			hdCardInitiator.setAccount(0);
			hdCardInitiator.setFinishRate(0);
			hdCardInitiator.setInitiateTime(new Date());
			hdCardInitiator.setTotalScore(0);
			hdCardInitiator.setStatus(0);
			hdCardInitiatorDao.save(hdCardInitiator);
		}
		
		return hdCardInitiator;
	}
	
	@Override
	public void update(HdCardInitiatorEntity hdCardInitiator){
		hdCardInitiatorDao.update(hdCardInitiator);
	}
	
	@Override
	public void delete(String id){
		hdCardInitiatorDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		hdCardInitiatorDao.deleteBatch(ids);
	}
	
}
